const path = require('path');
const webpack = require('webpack');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
// 清理 dist 文件夹
const CleanWebpackPlugin = require('clean-webpack-plugin');
// js压缩、优化插件
const TerserPlugin = require('terser-webpack-plugin');
// 抽取css extract-text-webpack-plugin不再支持webpack4，官方出了mini-css-extract-plugin来处理css的抽取
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
// 优化输入信息插件
const FirendlyErrorePlugin = require('friendly-errors-webpack-plugin');
const MinifyPlugin = require('babel-minify-webpack-plugin');

const config = require('./src/pages/pages'); // 多页面的配置项
let HTMLPlugins = [];
let Entries = {};

const MKT_CONFIG = require('./MKT_Config');
const BUILD_MODE  = process.env.BUILD_MODE.trim()
const isDev = BUILD_MODE === 'dev';
console.log('当前是否是测试环境：', isDev);
const outputTargetDir = `./dist`
// const outputTargetDir = `./dist/${BUILD_MODE}`
config.HTMLDirs.forEach(item => {
    let filename = `${item.page}.html`;
    if (item.dir) filename = `${item.dir}/${item.page}.html`;
    const htmlPlugin = new HTMLWebpackPlugin({
        title: item.title, // 生成的html页面的标题
        mktDomain: isDev ? MKT_CONFIG.devDomain : MKT_CONFIG.prodDomain,
        mktName: isDev ? MKT_CONFIG.devName : MKT_CONFIG.prodName,
        mktUrl: isDev ? MKT_CONFIG.devUrl : MKT_CONFIG.prodUrl,
        filename: filename, // 生成到dist目录下的html文件名称，支持多级目录（eg: `${item.page}/index.html`）
        template: path.resolve(__dirname,
        './public/index.html'), // 模板文件，不同入口可以根据需要设置不同模板
        chunks: [item.page, 'vendor',
        'common'], // html文件中需要要引入的js模块，这里的 vendor 是webpack默认配置下抽离的公共模块的名称
        dateTime: (new Date()).getTime(),
    });
    HTMLPlugins.push(htmlPlugin);
    Entries[item.page] = path.resolve(__dirname,
    `./src/pages/${item.page}/index.js`); // 根据配置设置入口js文件
});

module.exports = {
    mode: 'production',
    entry: Entries,
    output: {
        publicPath: '/',
        filename: 'sole/js/[name].[hash:8].js',
        path: path.resolve(__dirname, outputTargetDir),
        chunkFilename: 'sole/[id].[hash:8].js'
    },
    module: {
        rules: [{
                test: /\.vue$/, // 处理vue模块
                use: [{
                    loader: 'vue-loader',
                }],
            },
            {
                test: /\.js$/, //处理es6语法
                exclude: /node_modules/,
                use: [{
                    loader: 'babel-loader',
                    options: {
                        cacheDirectory: true,
                    }
                }]
            },
            {
                test: /\.css$/,
                // exclude: /node_modules/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader'
                ]
            }, {
                test: /\.less$/,
                // exclude: /node_modules/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader',
                    'less-loader',
                    {
                        loader: 'sass-resources-loader',
                        options: {
                            resources: path.resolve(__dirname,
                                './src/styles/veriable.less'),
                        }
                    },
                ]
            },
            {
                test: /\.(png|svg|jpg|gif)$/, // 处理图片
                use: {
                    loader: 'file-loader', // 解决打包css文件中图片路径无法解析的问题
                    options: {
                        // 打包生成图片的名字
                        name: '[name].[hash:8].[ext]',
                        // 图片的生成路径
                        outputPath: config.imgOutputPath,
                        publicPath: '/sole/img'
                    }
                }
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/, // 处理字体
                use: {
                    loader: 'file-loader',
                    options: {
                        outputPath: config.fontOutputPath,
                        publicPath: '/sole/css'
                    }
                }
            },
        ],
    },
    resolve: { // 设置模块如何被解析
        alias: {
            '@biztools': path.resolve(__dirname, './src/biztools'),
            '@components': path.resolve(__dirname, './src/components'),
            '@styles': path.resolve(__dirname, './src/styles'),
            '@store': path.resolve(__dirname, './src/store'),
            '@router': path.resolve(__dirname, './src/router'),
            '@assets': path.resolve(__dirname, './assets'),
            '@common': path.resolve(__dirname, './src/common'),
            '@server': path.resolve(__dirname, './src/server'),
            '@config': path.resolve(__dirname, './src/server/config'),
            '@views': path.resolve(__dirname, './src/views'),
            '@mock': path.resolve(__dirname, './src/mock'),
            '@constants': path.resolve(__dirname, './src/constants'),
            '@mixins': path.resolve(__dirname, './src/pages/page.js'),
            '@vuex': path.resolve(__dirname, './src/store'),
        },
        extensions: ['*', '.less', '.css', '.js', '.vue']
    },
    optimization: {
        splitChunks: {
            maxInitialRequests: 5,
            cacheGroups: {
                vendor: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendor',
                    chunks: 'all',
                    priority: -10,
                    enforce: true,
                },
                common: {
                    test: /[\\/]src[\\/](common|components)[\\/]/,
                    name: 'common',
                    chunks: 'all',
                    priority: 20,
                },
            }
        },
        minimizer: [
            new TerserPlugin({ // 压缩js
                cache: true,
                parallel: true,
                terserOptions: {
                    mangle: {
                        safari10: true,
                    },
                }
            }),
            new OptimizeCSSAssetsPlugin({ // 压缩css
                cssProcessorOptions: {
                    safe: true
                }
            })
        ]
    },
    plugins: [
        // 自动清理 dist 文件夹
        new CleanWebpackPlugin([outputTargetDir], {
            root: __dirname,
            verbose: true, //开启在控制台输出信息
            dry: false,
            allowExternal: true, // 允许删除根目录下文件夹中的内容
            beforeEmit: true, // 输出文件前清理干净
        }),
        new VueLoaderPlugin(),
        new FirendlyErrorePlugin(),
        new CopyWebpackPlugin([{
            from: path.resolve(__dirname, './public'),
            to: path.resolve(__dirname, outputTargetDir),
            ignore: ['*.html']
        }, ]),
        ...HTMLPlugins, // 利用 HTMLWebpackPlugin 插件合成最终页面
        new MiniCssExtractPlugin({
            filename: 'sole/css/[name].[chunkhash:8].css'
        }),
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('production'),
                'BUILD_MODE': JSON.stringify(`${BUILD_MODE}`),
            },
        }),
        new webpack.optimize.OccurrenceOrderPlugin(),
        new MinifyPlugin(),
    ]
};
